#!/usr/bin/env bash
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Prepares all the data needed for new ChromeDriver release for sending to the
# server.

set -eu

source "$(dirname "$0")/common.sh"
ensure_linux $0
ensure_release_root

version=$(cat ".version")
src=unzipped
tgt=packed

if [ ! -d "$src" -o ! -f "$src/.pulled" -o "$version" != "$(cat $src/.pulled)" ]
then
  echo "Nothing to pack in $0. Command 'nest pull' needs to be executed first!" >&2
  exit 1
fi

rm -rf $tgt
mkdir $tgt

notes_paths=(
  "../notes.txt"
  "../notes_${version}.txt"
  "./notes.txt"
  "./notes_${version}.txt"
  "${src}/notes.txt"
  "${src}/notes_${version}.txt"
  )

path_to_notes=""

for path in ${notes_paths[@]}
do
  if [ -f "$path" ]
  then
    path_to_notes="$path"
  fi
done

while [ "$#" -gt 0 ]
do
  case "$1" in
    --notes=*)
      path_to_notes=$(echo "$1" | sed -r 's#--notes=##')
      ;;
  esac
  shift
done

if [ ! -f "$path_to_notes" ]
then
  echo "Notes file not found: $path_to_notes" >&2
  echo "Usage: $0 [--notes=path-to-notes]" >&2
  exit 1
fi

if ! grep -Eq "ChromeDriver\s+$version" "$path_to_notes"
then
  echo "Error in $0. Notes file refers to different version than $version in $path_to_notes" >&2
  exit 1
fi


zip -j $tgt/chromedriver_linux64.zip $src/chromedriver_linux64/chromedriver
zip -j $tgt/chromedriver_mac64.zip $src/chromedriver_mac64/chromedriver
zip -j $tgt/chromedriver_mac64_m1.zip $src/chromedriver_mac64_m1/chromedriver_mac64/chromedriver
zip -j $tgt/chromedriver_win32.zip $src/chromedriver_win32/chromedriver.exe
echo -n "$version" > $tgt/latest
cp "$path_to_notes" "$tgt/notes.txt"
